<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>动态组件</title>
</head>

<body>
    <div id="app">
        <input type="button" value="切换到第1个组件" @click="TabCompent(1)">
        <input type="button" value="切换到第2个组件" @click="TabCompent(2)">
        <input type="button" value="切换到第3个组件" @click="TabCompent(3)">
        <keep-alive>
            <component :is="current"></component>
        </keep-alive>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue"></script>

    <script>
        var custom1 = Vue.component("custom1", {
            template: `
            <div @click="changeDivBg">我是第1个组件</div>
            `,
            methods: {
                changeDivBg(ev) {
                    ev.target.style.background = "red";
                }
            }
        });
        var custom2 = Vue.component("custom2", {
            template: `
            <div>我是第2个组件</div>
            `
        });
        var custom3 = Vue.component("custom3", {
            template: `
            <div>我是第3个组件</div>
            `
        });
        new Vue({
            el: "#app",
            data: {
                current: custom1
            },
            methods: {
                TabCompent(index) {
                    if (index == 1) {
                        this.current = custom1;
                    } else if (index == 2) {
                        this.current = custom2;
                    } else if (index == 3) {
                        this.current = custom3;
                    }
                }
            }
        });
    </script>

</body>

</html>